/**
 * 项目名：	Rumba Plan
 * 
 * 版权所有(C)，上海海鼎信息工程股份有限公司，2007，所有权利保留。
 * 
 * 文件名：	PrintServer.java
 * 模块说明：	
 * 修改历史：
 * Jun 8, 2007 - zhangyanbo - 创建。
 */
package com.hd123.rumba.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.log4j.lf5.util.StreamUtils;

import com.hd123.rumba.exception.BusinessException;
import com.hd123.rumba.report.IReportProvider;
import com.hd123.rumba.report.ReportFactory;
import com.hd123.rumba.request.ActionAbstractImpl;
import com.hd123.rumba.request.ActionConstants;
import com.hd123.rumba.request.Dictionary;
import com.hd123.rumba.request.FileTooLargeException;
import com.hd123.rumba.request.JspLib;
import com.hd123.rumba.util.StringUtil;

/**
 * @author zhangyanbo
 * 
 */
public class ReportServer extends ActionAbstractImpl {

  public String execute() throws Exception {
    String startnode = (String) dd.getFormValue("start");
    String url = ActionConstants.NOTIMPLEMENTED;
    if ("getData".equals(startnode))
      url = getData();
    else if ("getReport".equals(startnode))
      url = getReport();
    else if ("saveReport".equals(startnode)) {
      try {
        dd.prepareMultipartRequest(0x200000);
      } catch (FileTooLargeException e) {
        dd.addErrorText("文件大小超出了限制值" + 0x20000);
        return ActionConstants.FILETOOLARGE;
      }
      url = saveReport();
    }
    return url;
  }

  public String getData() throws Exception {
    String providerId = (String) dd.getFormValue("provider");
    IReportProvider provider = ReportFactory.getProvider(providerId);
    File dir = new File(JspLib.getTempExportDir(dd.getRequest()));
    dir.mkdirs();
    File file = new File(dir, StringUtil.createUuid() + ".xml");
    FileOutputStream out = new FileOutputStream(file);
    try {
      provider.getData(dd, out);
    } finally {
      out.close();
    }
    File zfile = new File(dir, file.getName() + ".zip");
    compressFile(file, zfile);
    dd.getResponse().setCharacterEncoding("utf-8");
    sendFile(dd.getResponse(), zfile);
    file.delete();
    zfile.delete();
    return ActionConstants.DIRECT;
  }

  public String getReport() throws Exception {
    String providerId = (String) dd.getFormValue("provider");
    IReportProvider provider = ReportFactory.getProvider(providerId);
    sendFile(dd.getResponse(), provider.getReport(dd));
    return ActionConstants.DIRECT;
  }

  public String saveReport() throws Exception {
    PrintWriter out = dd.getResponse().getWriter();
    String providerId = (String) dd.getFormValue("provider");
    try {
      IReportProvider provider = ReportFactory.getProvider(providerId);
      FileInputStream fin = new FileInputStream((File) dd.getFormValue("filename"));
      FileOutputStream fout = new FileOutputStream(provider.getReport(dd));
      try {
        StreamUtils.copy(fin, fout);
      } finally {
        fin.close();
        fout.close();
      }
      out.write("打印模版已保存到服务器。");
    } catch (Exception e) {
      out.write("错误:" + e.getMessage());
      Logger.getLogger(this.getClass()).error(e);
    }
    return ActionConstants.DIRECT;
  }

  private void sendFile(HttpServletResponse response, File file) throws IOException {
    FileInputStream in = new FileInputStream(file);
    response.setContentLength((int) file.length());
    OutputStream out = response.getOutputStream();
    try {
      StreamUtils.copy(in, out);
    } finally {
      in.close();
    }
  }

  private void compressFile(File file, File compressedFile) throws Exception {
    try {
      FileOutputStream fout = new FileOutputStream(compressedFile);
      ZipOutputStream zout = new ZipOutputStream(fout);
      zout.putNextEntry(new ZipEntry(file.getName()));
      FileInputStream fin = new FileInputStream(file);
      StreamUtils.copy(fin, zout);
      fin.close();
      zout.closeEntry();
      zout.close();
    } catch (IOException e) {
      throw new Exception("压缩文件出错：" + e);
    }
  }

  public static String getCodeBase() throws BusinessException {
    return JspLib.getStaticContent("rumba/activex/fr3c.dll") + "#version=1,0,4,1";
  }

  public static String getFilePath() throws BusinessException {
    return JspLib.getStaticContent("rumba/activex");
  }

  public static String getServerUrl(Dictionary dd) throws BusinessException {
    HttpServletRequest request = dd.getRequest();
    return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
  }

}
